package cn.lvxs.framework;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;

import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletRequestAttributeEvent;
import javax.servlet.ServletRequestAttributeListener;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionActivationListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import com.wabacus.config.ConfigLoadManager;
import com.wabacus.config.Config;
import com.wabacus.system.ReportRequest;

/**
 * Application Lifecycle Listener implementation class SessionListener
 *
 */
public final class SessionListener implements ServletContextListener, ServletContextAttributeListener, HttpSessionListener, HttpSessionAttributeListener, HttpSessionActivationListener, HttpSessionBindingListener, ServletRequestListener,ServletRequestAttributeListener {

    /**
     * Default constructor. 
     */
    public SessionListener() {
    }

	/**
     * @see ServletRequestListener#requestDestroyed(ServletRequestEvent)
     */
    public void requestDestroyed(ServletRequestEvent arg0) {
    }

	/**
     * @see HttpSessionAttributeListener#attributeAdded(HttpSessionBindingEvent)
     */
    public void attributeAdded(HttpSessionBindingEvent arg0) {
    }

	/**
	 * 应用程序初始化
     * @see ServletContextListener#contextInitialized(ServletContextEvent)
     */
    public void contextInitialized(ServletContextEvent arg0) {
    	HashMap<?, ?> OnlineSession=new HashMap<Object, Object>();
    	Application.put("OnlineSession",OnlineSession);
    	HashMap<?, ?> OnlineUserList=new HashMap<Object, Object>();
    	Application.put("OnlineUserList",OnlineUserList);
		Application.put("sysConfig",null);
		if(arg0.getServletContext().getContextPath()!=null){
			Config.webroot=arg0.getServletContext().getContextPath();
		}
		if(Config.webroot==null || Config.webroot.isEmpty()){
			Config.webroot="/";
		}
		if(arg0.getServletContext().getContextPath()!=null){
			Config.homeAbsPath=arg0.getServletContext().getRealPath("/");
		}
		if(Config.homeAbsPath==null || Config.homeAbsPath.isEmpty()){
			Config.homeAbsPath="/";
		}
    }

	/**
     * @see HttpSessionActivationListener#sessionDidActivate(HttpSessionEvent)
     */
    public void sessionDidActivate(HttpSessionEvent arg0) {
    }

	/**
     * @see HttpSessionBindingListener#valueBound(HttpSessionBindingEvent)
     */
    public void valueBound(HttpSessionBindingEvent arg0) {
    }

	/**
     * @see ServletContextAttributeListener#attributeAdded(ServletContextAttributeEvent)
     */
    public void attributeAdded(ServletContextAttributeEvent arg0) {
    }

	/**
     * @see ServletContextAttributeListener#attributeRemoved(ServletContextAttributeEvent)
     */
    public void attributeRemoved(ServletContextAttributeEvent arg0) {
    }

	/**
	 * 销毁Session时
     * @see HttpSessionListener#sessionDestroyed(HttpSessionEvent)
     */
    public void sessionDestroyed(HttpSessionEvent arg0) {
    	if(Application.get("OnlineSession")!=null){
    		HashMap<?, ?> OnlineSession=(HashMap<?, ?>)Application.get("OnlineSession");
	    	OnlineSession.remove(arg0.getSession().getId());
	    	Application.put("OnlineSession",OnlineSession);
    	}
    	if(Application.get("OnlineUserList")!=null){
    		HashMap<?, ?> OnlineUserList=(HashMap<?, ?>)Application.get("OnlineUserList");
    		OnlineUserList.remove(arg0.getSession().getId());
	    	Application.put("OnlineUserList",OnlineUserList);
    	}
    }

	/**
     * @see HttpSessionAttributeListener#attributeRemoved(HttpSessionBindingEvent)
     */
    public void attributeRemoved(HttpSessionBindingEvent arg0) {
    }

	/**
     * @see ServletRequestAttributeListener#attributeAdded(ServletRequestAttributeEvent)
     */
    public void attributeAdded(ServletRequestAttributeEvent arg0) {
    }

	/**
     * @see HttpSessionBindingListener#valueUnbound(HttpSessionBindingEvent)
     */
    public void valueUnbound(HttpSessionBindingEvent arg0) {
    }

	/**
     * @see HttpSessionActivationListener#sessionWillPassivate(HttpSessionEvent)
     */
    public void sessionWillPassivate(HttpSessionEvent arg0) {
    }

	/**
	 * 创建Session时
     * @see HttpSessionListener#sessionCreated(HttpSessionEvent)
     */
    @SuppressWarnings("unchecked")
	public void sessionCreated(HttpSessionEvent arg0) {
    	HashMap<String, HttpSession> OnlineSession;
    	if(Application.get("OnlineSession")!=null){
    		OnlineSession=(HashMap<String, HttpSession>)Application.get("OnlineSession");
    	}
    	else{
    		OnlineSession=new HashMap<String, HttpSession>();
    	}
    	OnlineSession.put(arg0.getSession().getId(),arg0.getSession());
    	Application.put("OnlineSession",OnlineSession);
    	if(Application.get("sysConfig")==null){
    	SystemConfig sysConfig = new SystemConfig();
    	try {
    		if(ConfigLoadManager.currentDynClassLoader!=null){
				Connection conn = Config.getInstance().getDataSource("").getConnection();
				Statement stmt = null;
				//从数据库中取得系统参数，并存放在Application中
				try {
					stmt = conn.createStatement();
					ResultSet rs = stmt
							.executeQuery("select * from SysConfig order by id");
					if (rs.next()) {
						sysConfig.setId(rs.getLong("ID"));
						sysConfig.setAllowfailtimes(rs.getLong("allowfailtimes"));
						sysConfig.setAllowoldpassword(rs.getLong("allowoldpassword") == 1);
						sysConfig.setAutolockdays(rs.getLong("autolockdays"));
						sysConfig.setInitpassword(rs.getString("initpassword"));
						sysConfig.setMeantimelogin(rs.getLong("meantimelogin"));
						sysConfig.setPassingscore(rs.getLong("passingscore"));
						sysConfig.setReminddays(rs.getLong("reminddays"));
						sysConfig.setValiddays(rs.getLong("validdays"));
						sysConfig.setUpdatetime(rs.getDate("updatetime"));
						sysConfig.setUpdateusername(rs.getString("updateusername"));
					}
					rs.close();
				} catch (SQLException e) {
				} finally {
					try {
						if (stmt != null) {
							stmt.close();
						}
					} catch (SQLException e) {
					}
					try {
						if (conn != null) {
							conn.close();
						}
					} catch (SQLException e) {
					}
				}
    		}
		} catch (Exception e) {
		}
		Application.put("sysConfig",sysConfig);
    	}
    }

	/**
     * @see HttpSessionAttributeListener#attributeReplaced(HttpSessionBindingEvent)
     */
    public void attributeReplaced(HttpSessionBindingEvent arg0) {
    }

	/**
     * @see ServletContextAttributeListener#attributeReplaced(ServletContextAttributeEvent)
     */
    public void attributeReplaced(ServletContextAttributeEvent arg0) {
    }

	/**
     * @see ServletRequestAttributeListener#attributeRemoved(ServletRequestAttributeEvent)
     */
    public void attributeRemoved(ServletRequestAttributeEvent arg0) {
    }

	/**
	 * 应用程序销毁时
     * @see ServletContextListener#contextDestroyed(ServletContextEvent)
     */
    public void contextDestroyed(ServletContextEvent arg0) {
        Application.destroy();
    }

	/**
     * @see ServletRequestAttributeListener#attributeReplaced(ServletRequestAttributeEvent)
     */
    public void attributeReplaced(ServletRequestAttributeEvent arg0) {
    }

	/**
     * @see ServletRequestListener#requestInitialized(ServletRequestEvent)
     */
    public void requestInitialized(ServletRequestEvent arg0) {
    }
	
}
